import { app, BrowserWindow, screen, ipcMain, dialog, globalShortcut, OpenDialogOptions, Menu } from 'electron';
import * as path from 'path';
import * as url from 'url';

let win: BrowserWindow, serve;
const args = process.argv.slice(1);
serve = args.some(val => val === '--serve');

function createWindow() {

  const electronScreen = screen;
  const size = electronScreen.getPrimaryDisplay().workAreaSize;
  const iconv = require('iconv-lite');
  // Convert from an encoded buffer to js string.
  const str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251');

  // Convert from js string to an encoded buffer.
  const buf = iconv.encode('Sample input string', 'win1251');

  // Check if encoding is supported
  iconv.encodingExists('us-ascii');
  // Create the browser window.
  win = new BrowserWindow({
    x: (size.width - 800) / 2,
    y: (size.height - 600) / 2,
    width: 800,
    height: 600,
    frame: false,
    title: 'angular for electron',
    webPreferences: { webSecurity: false }
  });

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store window
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
  });

  if (serve) {
    require('electron-reload')(__dirname, {
      electron: require(`${__dirname}/node_modules/electron`)
    });
    win.loadURL('http://localhost:4200');
  } else {
    win.loadURL(url.format({
      pathname: path.join(__dirname, 'dist/index.html'),
      protocol: 'file:',
      slashes: true
    }));
  }

  // 去掉默认菜单栏
  Menu.setApplicationMenu(null);

  // 注册打开控制台的快捷键
  globalShortcut.register('ctrl+shift+p', function () {
    const wind = BrowserWindow.getFocusedWindow();
    if (wind) {
      wind.webContents.openDevTools();
    }
  });

  win.show();

  // win.webContents.openDevTools();
}

ipcMain.on('selectfileordirectory', (_event, _args: OpenDialogOptions) => {
  let type: string;
  if (_args.properties.includes('openFile')) {
    type = 'file';
  } else if (_args.properties.includes('openDirectory')) {
    type = 'directory';
  }
  dialog.showOpenDialog(_args, files => _event.sender.send('selectedfileordirectory'
  , {type: type, result: files}));
});

try {

  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.on('ready', createWindow);

  app.on('will-quit', () => {
    // 注销快捷键
    globalShortcut.unregister('ctrl+shift+p');

    // 注销所有快捷键
    globalShortcut.unregisterAll();
  });

  // Quit when all windows are closed.
  app.on('window-all-closed', () => {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });

  app.on('activate', () => {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
      createWindow();
    }
  });

} catch (e) {
  // Catch Error
  // throw e;
}
